package com.lisn.sghttps

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.io.ByteArrayOutputStream
import java.net.URL
import java.security.KeyStore
import java.security.cert.CertificateFactory
import javax.net.ssl.*

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    // 懒加载初始化view
    val mButPay by lazy {
        but_pay
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mButPay.onClick() {
            Log.e(TAG, "onCreate: ")

            //子线程请求接口
            sendHttps()
        }


    }

    private fun sendHttps() {
        doAsync {

            // 1.创建SSL上下文对象设置信任管理器
            val sslContext = SSLContext.getInstance("TLS")
            //获取信任管理器工厂
            val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            //初始化工厂
            val ks = KeyStore.getInstance(KeyStore.getDefaultType())
            //清空默认证书，设置自己的证书
            ks.load(null)

            val cf = CertificateFactory.getInstance("X.509")
            val open = assets.open("alipay.cer")
            val cert = cf.generateCertificate(open)
            ks.setCertificateEntry("alipay", cert)
            tmf.init(ks)

            val tm = tmf.trustManagers
            sslContext.init(null, tm, null)

            val url = URL("https://192.168.141.36:8443/alipay.json")
            var connection: HttpsURLConnection = url.openConnection() as HttpsURLConnection

            // 使用信任管理器
            connection.sslSocketFactory = sslContext.socketFactory

            //校验主机名
            connection.hostnameVerifier = MyHostnameVerifier()


            // 获取服务器返回的流
            val ins = connection.inputStream
            val bos = ByteArrayOutputStream()
            val buffer = ByteArray(1024)
            var len = 0
            len = ins.read(buffer)
            while (len != -1) {
                bos.write(buffer, 0, len)
                len = ins.read(buffer)
            }
            val result = bos.toString()
            println("服务器返回=" + result)
            Log.e(TAG, "sendHttps: 服务器返回=" + result)

        }
    }

    private class MyHostnameVerifier : HostnameVerifier {
        // 主机名校验：当发现是公司的接口返回true
        override fun verify(hostname: String?, session: SSLSession?): Boolean {
            Log.e("TAG", "verify: hostname " + hostname)
            return true
        }

    }
}